
const {readFileSync}=require('fs');
const yaml = require('js-yaml');
const {join}=require('path');
//配置公共基础文件路径
const YAML_CONFIG_FILENAME = 'config.yml';
const filePath = join(__dirname, '../config', YAML_CONFIG_FILENAME);
//根据环境变量读取配置文件
const envFilePath = join(
  __dirname,
  '../config',
  `config.${process.env.NODE_ENV || 'development'}.yml`,
);
//默认配置文件读取
const commonConfig = yaml.load(readFileSync(filePath, 'utf-8')) 
//开发环境和生产环境配置文件读取
const envConfig = yaml.load(readFileSync(envFilePath, 'utf-8')) 

// 递归合并对象，将公共部分和环境变量部分合并
const mergeDeep = (target, source) => {
    const isObject = (obj) => obj && typeof obj === 'object';
    if (!isObject(target) || !isObject(source)) {
      return source;
    }
    Object.keys(source).forEach((key) => {
      const targetValue = target[key];
      const sourceValue = source[key];
      if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
        target[key] = targetValue.concat(sourceValue);
      } else if (isObject(targetValue) && isObject(sourceValue)) {
        target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue);
      } else {
        target[key] = sourceValue;
      }
    });
    return target;
  };
// 加载配置文件,config有一个load方法需要返回一个函数
module.exports=mergeDeep(commonConfig, envConfig)
